package com.study.jvm.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Description:
 * User: tan
 * DateTime: 2018/1/24 10:32
 */
public class StringUnsafe {


    public static void main(String[] args) throws Exception {
        Unsafe unsafe = getUnsafeInstance();

        StringDomain domain = new StringDomain();


        Field valueInString = String.class.getDeclaredField("value");

        long offset = unsafe.objectFieldOffset(valueInString);

        char[] values = (char[]) unsafe.getObject(domain.str, offset);
        System.out.println(values);
        char[] values1 = new char[domain.str.length()];

        unsafe.copyMemory(domain.str, offset, values1, unsafe.arrayBaseOffset(char[].class), domain.str.length() * 8);
        System.out.println(values1);

//        long base = unsafe.arrayBaseOffset(char[].class);
//
//        long scale = unsafe.arrayIndexScale(char[].class);
//
//        for(int i=0; i<scale; i++){
//             char ch = unsafe.getChar(base);
//             System.out.println(ch);
//        }


    }

    public static Unsafe getUnsafeInstance() throws Exception {
        Field unsafeStaticField =
                Unsafe.class.getDeclaredField("theUnsafe");
        unsafeStaticField.setAccessible(true);
        return (Unsafe) unsafeStaticField.get(Unsafe.class);
    }
}

class StringDomain {
    public final String str = "123";
    public String internalStr;
}
